import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class BuyerManageFrame extends JFrame {
    private JTable buyerTable;
    private DefaultTableModel tableModel;

    public BuyerManageFrame() {
        setTitle("采购员管理");
        setSize(600, 400);
        setLocationRelativeTo(null);

        // 表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("采购员编号");
        tableModel.addColumn("姓名");
        tableModel.addColumn("性别");
        tableModel.addColumn("业绩");

        buyerTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(buyerTable);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addBtn = new JButton("添加");
        JButton editBtn = new JButton("修改");
        JButton deleteBtn = new JButton("删除");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        loadBuyerData();

        // 事件监听
        addBtn.addActionListener(e -> {
            new BuyerEditDialog(null).setVisible(true);
            loadBuyerData();
        });

        editBtn.addActionListener(e -> {
            int selectedRow = buyerTable.getSelectedRow();
            if (selectedRow >= 0) {
                String bno = (String) tableModel.getValueAt(selectedRow, 0);
                new BuyerEditDialog(bno).setVisible(true);
                loadBuyerData();
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的行", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        deleteBtn.addActionListener(e -> deleteBuyer());
        refreshBtn.addActionListener(e -> loadBuyerData());
    }

    private void loadBuyerData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM buy")) {

            while (rs.next()) {
                tableModel.addRow(new Object[]{
                        rs.getString("bno"),
                        rs.getString("bname"),
                        rs.getString("bsex"),
                        rs.getString("bscore")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteBuyer() {
        int selectedRow = buyerTable.getSelectedRow();
        if (selectedRow >= 0) {
            String bno = (String) tableModel.getValueAt(selectedRow, 0);

            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确定要删除采购员 " + bno + " 吗?",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement pstmt = conn.prepareStatement("DELETE FROM buy WHERE bno = ?")) {

                    pstmt.setString(1, bno);
                    int affectedRows = pstmt.executeUpdate();

                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "删除成功");
                        loadBuyerData();
                    }
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(this, "删除失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的行", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}

class BuyerEditDialog extends JDialog {
    private JTextField bnoField, bnameField, bsexField, bscoreField;
    private boolean isEditMode;

    public BuyerEditDialog(String bno) {
        if (bno == null) {
            setTitle("添加采购员");
            isEditMode = false;
        } else {
            setTitle("修改采购员");
            isEditMode = true;
        }

        setSize(400, 250);
        setModal(true);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(4, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(new JLabel("采购员编号:"));
        bnoField = new JTextField();
        if (isEditMode) bnoField.setEditable(false);
        panel.add(bnoField);

        panel.add(new JLabel("姓名:"));
        bnameField = new JTextField();
        panel.add(bnameField);

        panel.add(new JLabel("性别:"));
        bsexField = new JTextField();
        panel.add(bsexField);

        panel.add(new JLabel("业绩:"));
        bscoreField = new JTextField();
        panel.add(bscoreField);

        JButton saveBtn = new JButton("保存");
        saveBtn.addActionListener(e -> saveBuyer());

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);

        add(panel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        if (isEditMode) {
            loadBuyerData(bno);
        }
    }

    private void loadBuyerData(String bno) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM buy WHERE bno = ?")) {

            pstmt.setString(1, bno);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                bnoField.setText(rs.getString("bno"));
                bnameField.setText(rs.getString("bname"));
                bsexField.setText(rs.getString("bsex"));
                bscoreField.setText(rs.getString("bscore"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void saveBuyer() {
        String bno = bnoField.getText().trim();
        String bname = bnameField.getText().trim();
        String bsex = bsexField.getText().trim();
        String bscore = bscoreField.getText().trim();

        // 验证输入
        if (bno.isEmpty() || bname.isEmpty()) {
            JOptionPane.showMessageDialog(this, "采购员编号和姓名不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            PreparedStatement pstmt;

            if (isEditMode) {
                pstmt = conn.prepareStatement(
                        "UPDATE buy SET bname=?, bsex=?, bscore=? WHERE bno=?");
                pstmt.setString(1, bname);
                pstmt.setString(2, bsex);
                pstmt.setString(3, bscore);
                pstmt.setString(4, bno);
            } else {
                pstmt = conn.prepareStatement(
                        "INSERT INTO buy (bno, bname, bsex, bscore) VALUES (?, ?, ?, ?)");
                pstmt.setString(1, bno);
                pstmt.setString(2, bname);
                pstmt.setString(3, bsex);
                pstmt.setString(4, bscore);
            }

            int affectedRows = pstmt.executeUpdate();

            if (affectedRows > 0) {
                JOptionPane.showMessageDialog(this, "保存成功");
                dispose();
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}